<?php
class Review extends AppModel {
	var $name = 'Review';
	var $useTable = 'reviews';
	const USER_TYPE_OWNER = 'owner';
	const USER_TYPE_JOINED = 'joined';
	const USER_TYPE_NORMAL = 'normal';

	var $belongTo = array(
		'User' => array(
			'class' => 'User',
			'foreignKey' => 'user_id',
		)
	);

	/**
	 * Add new review
	 * @param $data
	 * @return array
	 */
	function add ($data) {
		$default = array(
			'id' => null,
			'course_id' => 0,
			'user_id' => 0,
			'content' => '',
			'del_flg' => 0,
			'user_type' => self::USER_TYPE_NORMAL,
			'created' => date('Y-m-d H:i:s'),
			'modified' => date('Y-m-d H:i:s')
		);

		$data = array_merge($default, $data);
		return $this->save($data);
	}

	/**
	 * Get list reviews belong to course, if $getOptionOnly true, return options for query
	 *
	 * @param array $options
	 * @param bool $getOptionOnly
	 * @return array
	 */
	function getList ($options = array(), $getOptionOnly = false) {
		$default = array(
			'conditions' => array(
				$this->alias . '.del_flg' => 0,
			),
			'fields' => array(
				$this->alias .'.*',
				'Profile.*',
			),
			'limit' => 2,
			'order' => $this->alias . '.created DESC',
			'joins' => array(
				array(
					'table' => 'profiles',
					'alias' => 'Profile',
					'type' => 'INNER',
					'conditions' => array(
						$this->alias.'.user_id = Profile.user_id AND Profile.del_flg = 0'
					)
				)
			)
		);

		$options = array_merge($default, $options);
		if ($getOptionOnly) {
			return $options;
		}

		return $this->find('all', $options);
	}

	function updateDelFlg($reviewId, $userId) {
		$options = array(
			'conditions' => array(
				$this->alias . '.id' => $reviewId,
				$this->alias . '.user_id' => $userId,
			)
		);
		if ($this->find('count', $options)) {
			return $this->updateAll(array('del_flg' => 1), array('id' => $reviewId));
		} else {
			return false;
		}
	}
}